package com.liuxin.mycontactdemo.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.liuxin.mycontactdemo.R;
import com.liuxin.mycontactdemo.dbhelper.ContactOpenHelper;
import com.liuxin.mycontactdemo.provider.ContactProvider;
import com.liuxin.mycontactdemo.untils.ToastUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class AddContactActivity extends AppCompatActivity {

    @InjectView(R.id.addNameEt)
    EditText addNameEt;
    @InjectView(R.id.addPhoneEt)
    EditText addPhoneEt;
    @InjectView(R.id.addEmailEt)
    EditText addEmailEt;
    @InjectView(R.id.addQQEt)
    EditText addQQEt;
    @InjectView(R.id.addBtn)
    Button addBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contact);
        ButterKnife.inject(this);
    }

    @OnClick(R.id.addBtn)
    public void onViewClicked() {
        addContact();
        finish();
    }

    private void addContact() {
        ContentValues cv=new ContentValues();
        cv.put(ContactOpenHelper.ContactTable.NAME,addNameEt.getText().toString());
        cv.put(ContactOpenHelper.ContactTable.PHONE,addPhoneEt.getText().toString());
        cv.put(ContactOpenHelper.ContactTable.EMAIL,addEmailEt.getText().toString());
        cv.put(ContactOpenHelper.ContactTable.QQ,addQQEt.getText().toString());
        //判断添加联系人是否已存在

        Cursor cursor=getContentResolver().query(ContactProvider.URI_CONTACT,null,"name=?",new String[]{addNameEt.getText().toString()},null);
        if(cursor.getCount()!=0)
        {
            ToastUtils.showToastSafe(this,"该联系人已存在！");
        }
        else {
            getContentResolver().insert(ContactProvider.URI_CONTACT,cv);
            ToastUtils.showToastSafe(this,"联系人已添加！");
        }
    }
}
